package com.cunshe.service;

import com.cunshe.dao.MemorabiliaDao;
import com.cunshe.domain.Memorabilia;
import com.cunshe.exception.BizException;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MemorabiliaService {

    @Autowired
    private MemorabiliaDao memorabiliaDao;

    @Transactional(rollbackFor = Exception.class)
    public int insert(Memorabilia record) throws BizException {
        if(record.getType() != 1 && record.getType() != 2){
            throw new BizException("类型错误");
        }
        if(record.getType() == 1){
            Memorabilia memorabilia = get(record.getType(), record.getMdate());
            if(memorabilia != null){
                throw new BizException("年份已存在");
            }
        } else {
            String year = record.getMdate().split("-")[0];
            Memorabilia memorabilia = get(1, year);
            if(memorabilia == null){
                throw new BizException("年份不存在");
            }
        }
        memorabiliaDao.insert(record);

        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        return memorabiliaDao.delete(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public int update(Memorabilia record) {
        return memorabiliaDao.update(record);
    }

    public Memorabilia get(Long id) {
        return list(Memorabilia.builder().id(id).build())
                .stream()
                .findFirst()
                .orElse(null);
    }

    public List<Memorabilia> get(int type) {
        return list(Memorabilia.builder().type(type).build());
    }

    public Memorabilia get(int type, String mdate) {
        return list(Memorabilia.builder().type(type).mdate(mdate).build())
                .stream()
                .findFirst()
                .orElse(null);
    }

    public List<Memorabilia> get2(int type, String mdate) {
        return list(Memorabilia.builder().type(type).mdate(mdate).build());
    }

    public List<Memorabilia> list(Memorabilia record) {
        return memorabiliaDao.list(record);
    }

}